//
//  MYGChatFireCell.swift
//  MYGrow
//
//  Created by 小火科技 on 2024/3/14.
//

import UIKit
import SVGKit
import QMUIKit

class MYGChatFireCell: UITableViewCell {
    // MARK: - Property
    var model: MYGChatFireCellModel? {
        didSet {
            guard let model = model else {
                return
            }
            
            reloadLayout()
            
            if model.isLeft {
                fireButton.setTitle("您已查看过此消息", for: .selected)
            } else {
                fireButton.setTitle("对方已查看过此消息", for: .selected)
            }
            
            if model.isLeft == false {
                self.avatar.sd_setImage(with: URL(string: MYGUserManager.user?.doctor.avatar), placeholderImage: UIImage(named: "resum_head"))
            }else {
                if model.avatar.contains("http") {
                    avatar.sd_setImage(with: URL(string: model.avatar))
                } else {
                    avatar.image = UIImage(named: "head")
                }
            }
            
//            if model.avatar.contains("http") {
//                avatar.sd_setImage(with: URL(string: model.avatar))
//            } else {
//                if let data = UserDefaults.standard.data(forKey: model.avatar) {
//                    guard let svgImage = SVGKImage(data: data) else {
//                        return
//                    }
//                    
//                    self.avatar.image = svgImage.uiImage
//                } else {
//                    DispatchQueue.global().async {
//                        let url = URL(string: model.avatar)!
//                        guard let data = try? Data(contentsOf: url) else {
//                            return
//                        }
//                        
//                        UserDefaults.standard.setValue(data, forKey: model.avatar)
//                        UserDefaults.standard.synchronize()
//                        guard let svgImage = SVGKImage(data: data) else {
//                            return
//                        }
//                
//                        DispatchQueue.main.async {
//                            self.avatar.image = svgImage.uiImage
//                        }
//                    }
//                }
//            }
//            if !model.isLeft {
//                self.avatar.sd_setImage(with: URL(string: MYGUserManager.user?.doctor.avatar), placeholderImage: UIImage(named: "resum_head"))
//            }
            nameLabel.text = model.name
            
            fireButton.isSelected = model.isRead
        }
    }
    
    var reloadAction: (()->Void)?
    var playAction: ((MYGChatVoiceCellModel)->Void)?
    var cancelPlayAction: (()->Void)?
    private var bubbleImageView: UIView?
    // MARK: - init
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        selectionStyle = .none
        configUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - UI
    private func configUI() {
        contentView.addSubview(avatar)
        contentView.addSubview(nameLabel)
        contentView.addSubview(fireButton)
        contentView.bringSubviewToFront(nameLabel)
        reloadLayout()
    }
    
    private func reloadLayout() {
        guard let isLeft = model?.isLeft else {
            return
        }
        
        avatar.snp.remakeConstraints { make in
            if isLeft {
                make.left.equalToSuperview().offset(25)
            } else {
                make.right.equalToSuperview().inset(25)
            }
            make.top.equalToSuperview().offset(20)
            make.width.height.equalTo(36)
        }
        
        nameLabel.snp.remakeConstraints { make in
            if isLeft {
                make.left.equalTo(avatar.snp.right).offset(10)
            } else {
                make.right.equalTo(avatar.snp.left).offset(-10)
            }
            make.top.equalTo(avatar.snp.top)
        }
        
        fireButton.snp.remakeConstraints { make in
            if isLeft {
                make.left.equalTo(avatar.snp.right).offset(10)
            } else {
                make.right.equalTo(avatar.snp.left).offset(-10)
            }

            make.bottom.equalToSuperview().inset(5)
        }
        
        contentView.snp.remakeConstraints { make in
            make.width.equalTo(screenWidth)
            make.height.equalTo(141)
        }
    }
    
    // MARK: - lazy load
    private lazy var avatar: UIImageView = {
        let imgV = UIImageView()
        imgV.layer.masksToBounds = true
        imgV.layer.cornerRadius = 18
        return imgV
    }()
    
    private lazy var nameLabel: UILabel = {
        let label = UILabel()
        label.font = .regular(16)
        label.textColor = .rgba(38, 38, 40, 1)
        label.text = "系统"
        return label
    }()
    
    private(set) lazy var fireButton: QMUIButton = {
        let btn = QMUIButton()
        btn.setImage(UIImage(named: "Chat/unread"), for: .normal)
        btn.setImage(UIImage(named: "Chat/read"), for: .selected)
        btn.setTitle("按住查看阅后即焚", for: .normal)

        btn.setTitleColor(.rgba(104, 104, 104, 1), for: .normal)
        
        btn.titleLabel?.font = .regular(12)
        btn.titleLabel?.textColor = .rgba(104, 104, 104, 1)
        btn.imagePosition = .top
        btn.spacingBetweenImageAndTitle = 8
        
        btn.contentVerticalAlignment = .bottom
        
        btn.addTarget(self, action: #selector(showImage), for: .touchUpInside)
        
        let press = UILongPressGestureRecognizer(target: self, action: #selector(pressImage))
//        btn.addGestureRecognizer(press)
        press.minimumPressDuration = 0.5
        return btn
    }()
}

extension MYGChatFireCell {
    @objc
    private func showImage() {
//        guard let model = model?.model as? MYGChatImageCellModel else {
//            return
//        }
        if fireButton.isSelected {
            return
        }
        
        if let model = model?.model as? MYGChatImageCellModel {
            let vc = MYGFireImageViewController(isLeft: model.isLeft, imageUrl: model.imageUrl, localImage: model.localImage)
            UIViewController.currentViewController?.present(vc, animated: false)
            vc.seeAction = {[weak self] in
                self?.fireButton.isSelected = true
                self?.model?.fireAction?()
            }
        }
        
        if let model = model?.model as? MYGChatContentCellModel {
            let vc = MYGFireMessageViewController(model: model)
            UIViewController.currentViewController?.present(vc, animated: false)
            vc.seeAction = {[weak self] in
                if model.isLeft {
                    self?.fireButton.isSelected = true
                    self?.model?.fireAction?()
                }
            }
        }

        if let model = model?.model as? MYGChatVoiceCellModel {
            let vc = MYGFireVoiceViewController(model: model)
            UIViewController.currentViewController?.present(vc, animated: false)
            vc.seeAction = {[weak self] in
                if model.isLeft {
                    self?.fireButton.isSelected = true
                    self?.model?.fireAction?()
                }
            }
        }
    }
    
    @objc
    private func pressImage(_ press: UILongPressGestureRecognizer) {
        if let model = model?.model as? MYGChatVoiceCellModel {
            if fireButton.isSelected {
                return
            }
            
            switch press.state {
            case .began:
                self.playAction?(model)
            case .changed:
                break
            case .ended:
                if model.isLeft {
                    fireButton.isSelected = true
                    model.isFire = true
                    self.model?.fireAction?()
                }
                self.cancelPlayAction?()
            default:
                break
            }
            
            return
        }
        
        guard let model = model?.model as? MYGChatContentCellModel else {
            return
        }
        if fireButton.isSelected {
            return
        }
        
        switch press.state {
        case .began:
            let imageView = UIView()
            imageView.backgroundColor = .white
            imageView.layer.shadowColor = UIColor.black.cgColor
            imageView.layer.shadowOpacity = 0.3
            imageView.layer.cornerRadius = 5
            UIViewController.currentViewController?.view.addSubview(imageView)
            
            let label = UILabel()
            label.font = .regular(12)
            label.textColor = .black
            label.numberOfLines = 0
            label.text = model.content
            imageView.addSubview(label)
            
            let size = model.content.labelSize(size: CGSize(width: 120, height: CGFLOAT_MAX), font: .regular(12))
            label.size = size
            imageView.size = CGSize(width: size.width+24, height: size.height+30)
            label.center = imageView.center
            
            fireButton.layoutIfNeeded()
            let point = fireButton.convert(CGPointZero, to: UIViewController.currentViewController?.view!)
            
            let isLeft = self.model?.isLeft ?? false
            
            imageView.center = CGPointMake(!isLeft ? point.x-(imageView.width/2)-5 : point.x + fireButton.width + 5 + imageView.width/2, point.y+fireButton.height/2)
            bubbleImageView = imageView
        case .changed:
            break
        case .ended:
            bubbleImageView?.removeFromSuperview()
            if model.isLeft {
                fireButton.isSelected = true
                model.isFire = true
                self.model?.fireAction?()
            }
            
        default:
            break
        }
    }
}

